package com.mobiusws.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.mobiusws.util.DateUtil;

public class ExportToExcel extends HttpServlet {
	private static final long serialVersionUID = 2595261807932102942L;
	// ENCODING
	private final String ENCODING = "ISO-8859-1";
	// CONTENT_TYPE
	private final String CONTENT_TYPE = "text/html;charset=ISO-8859-1";

	private String path = File.separator + "opt" + File.separator + "GK2"
			+ File.separator + "out_report" + File.separator;
	// private String path = "E:"+File.separator+"out_report"+File.separator;
	// downloadFileDir
	private String downloadFileDir = "510_1" + File.separator;
	// downloadFile subDir
	private String downloadSubDir = "xlsx" + File.separator;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
		try {

			// set request character encoding
			req.setCharacterEncoding(ENCODING);
			// get filename from request
			String fileName = req.getParameter("fileName");
			// query flag, create file first
			String bQuery = req.getParameter("bQuery");
			if("E".equals(bQuery)) {
			} else if("C".equals(bQuery)) {
				path = File.separator + "opt" + File.separator + "GK2" + File.separator + "portal" + File.separator + "querydata" + File.separator;

			} else if("T".equals(bQuery)) {
				String suffix = req.getParameter("suffix");
				String s_msisdn = req.getParameter("smsisdn");
				String  startDate = req.getParameter("startDate");
				String  endDate = req.getParameter("endDate");
				
//				System.out.println("get startDate:" + req.getParameter("startDate") + ",endDate:"+req.getParameter("endDate") +" ,after:"+startDate+",endDate:"+endDate);
				
				fileName = s_msisdn + "_" + startDate + "_" + endDate + suffix;
				path = File.separator + "opt" + File.separator + "GK2" + File.separator + "portal" + File.separator + "querydata" + File.separator;

//				System.out.println("path:" + path + ",filename:"+fileName);
			} else if("H".equals(bQuery)){
				path = File.separator + "opt" + File.separator + "GK2"
				+ File.separator + "out_report" + File.separator;
				
			} else {
				path = File.separator + "opt" + File.separator + "GK2"
				+ File.separator + "out_report" + File.separator;
				if (fileName.substring(fileName.lastIndexOf("_") + 1,
						fileName.lastIndexOf(".")).indexOf("-") <= 0) {
					long longStr = Long.parseLong(fileName.substring(
							fileName.lastIndexOf("_") + 1,
							fileName.lastIndexOf(".")));
					Date d = new Date();
					d.setTime(longStr);
					DateUtil dateUtil=new DateUtil();
					String date_str = DateUtil.date2String("yyyyMMdd", d);
					fileName = fileName.replaceFirst(String.valueOf(longStr),
							date_str);
				}
			}

			if (fileName == null || fileName.trim().equals("")) {
				// set ContentType of response
				resp.setContentType(CONTENT_TYPE);
				resp.setHeader("Pragma", "no-cache");
				// error message
				PrintWriter out = resp.getWriter();
				if("E".equals(bQuery)) {
					out.println("<font color=red>The size of export is more then 10,000, can't export it!</font>");
				} else {
					out.println("<font color=red>Valid File Name</font>");
				}

				out.close();
			} else {
				// get full path of filename
				downloadFileDir = GetDBConnection() + File.separator;
				fileName = fileName.replaceAll("-", "");
				downloadSubDir = fileName
						.substring(fileName.lastIndexOf(".") + 1)
						+ File.separator;
				String fullFileName = path + downloadFileDir + downloadSubDir
						+ fileName;
				File file = new File(fullFileName);
				System.out.println("download file:" + fullFileName
						+ ",is exists:" + file.exists());
				if (!file.exists()) {
					// set ContentType of response
					resp.setContentType(CONTENT_TYPE);
					resp.setHeader("Pragma", "public");
					resp.setHeader("Cache-Control",
							"must-revalidate, post-check=0, pre-check=0");
					resp.setHeader("Cache-Control", "public");
					resp.setDateHeader("Expires", 0);
					// error message
					PrintWriter out = resp.getWriter();
					out.println("<font color=red>File does not exists or is creating or file is too large.</font>");
					out.close();
				} else {
					// get the file content type to set ContentType of response
					String contentType = getServletContext().getMimeType(
							fullFileName);
					if (contentType == null)
						contentType = "application/octet-stream";
					resp.setContentType(contentType);
					resp.setHeader("Pragma", "no-chache");
					resp.setHeader("Pragma", "public");
					resp.setHeader("Cache-Control",
							"must-revalidate, post-check=0, pre-check=0");
					resp.setHeader("Cache-Control", "public");
					resp.setHeader("Cache-Control", "no-chache");
					resp.setDateHeader("Expires", 0);
					resp.setHeader("content-disposition",
							"attachment;filename=\"" + fileName+"\"");
					InputStream is = null;
					OutputStream os = null;
					try {
						is = new BufferedInputStream(new FileInputStream(
								fullFileName));
						// ByteArrayOutputStream
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						// BufferedOutputStream
						os = new BufferedOutputStream(resp.getOutputStream());
						// buffer
						byte[] buffer = new byte[4 * 1024];// 4k Buffer
						int read = 0;
						// read file to input stream
						while ((read = is.read(buffer)) != -1) {
							baos.write(buffer, 0, read);
						}
						// write to output stream response
						os.write(baos.toByteArray());
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						// close os,is
						if (os != null)
							os.close();
						if (is != null)
							is.close();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String GetDBConnection() {
		String url = "";
		Context ctx = null;
		Connection conn = null;

		try {
			ctx = new InitialContext();
			DataSource ds = (DataSource) ctx
					.lookup("java:comp/env/jdbc/dbxDataSource");
			conn = ds.getConnection();
			url = conn.toString().split(",")[0];
			url = url.substring(url.indexOf("_") + 1, url.indexOf("?"));
		} catch (SQLException e) {
			e.getMessage();
		} catch (NamingException e) {
			e.getMessage();
		} finally {
			if (conn == null) {
				System.out
						.println("Didn't get connection, which probably means that no Driver accepted the URL");
			} else {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		return url;
	}

	
}
